<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function food(name, price, ingredients) {
            this.name = name,
                this.price = price,
                this.ingredients = ingredients || []
        }
        food.prototype.addIngredient = function (name, weight) {
            this.ingredients.push({ name, weight })
        }
        food.prototype.removeIngredient = function (name) {
            this.ingredients.forEach((ele, index) => {
                if (ele.name === name) {
                    this.ingredients.splice(index, 1)
                }
            });
        }
        food.prototype.calculateTotalWeight = function () {
            return this.ingredients.reduce((prev, ele) => {
                return prev + ele.weight
            }, 0)
        }
        food.prototype.toString = function () {
            var str = '名称：' + this.name + '，价格：' + this.price + '，原料：';
            if (this.ingredients.length === 0) {
                str += '无';
            } else {
                str += this.ingredients.map(function (item) {
                    return item.name + '(' + item.weight + 'g)';
                }).join('，');
            }
            return str;
        }

        var food1 = new food('汉堡', 20);
        food1.addIngredient('牛肉', 100);
        food1.addIngredient('面包', 50);
        food1.removeIngredient('面包');
        console.log(food1.toString()); // 输出：名称：汉堡，价格：20，原料：牛肉(100g)

        var food2 = new food('披萨', 30, [
            { name: '面粉', weight: 200 },
            { name: '芝士', weight: 50 },
            { name: '番茄酱', weight: 30 }
        ]);
        console.log(food2.toString()); 
    </script>
</body>

</html>